package com.vrv.app.main;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.vrv.app.AppContext;
import com.vrv.app.R;
import com.vrv.app.entity.Category;

public class MainActivity extends SherlockActivity {

	private Context mContext = MainActivity.this;

	@ViewInject(R.id.gv_category)
	private GridView categoryGridView;

	private List<Category> categories = new ArrayList<Category>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ViewUtils.inject(this); // 注入view和事件

		try {
			categories = AppContext.db.findAll(Selector.from(Category.class));
			CategoryAdapter adapter = new CategoryAdapter(mContext, categories);
			categoryGridView.setAdapter(adapter);
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 使用SherlockActivity的menu
	 * 
	 * @see com.actionbarsherlock.app.SherlockActivity#onCreateOptionsMenu(com.actionbarsherlock.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	class CategoryAdapter extends BaseAdapter {
		// 定义Context
		private Context mContext;

		private List<Category> dataSource = null;

		public CategoryAdapter(Context c, List<Category> categories) {
			mContext = c;
			dataSource = categories;
		}

		// 获取图片的个数
		public int getCount() {
			return dataSource.size();
		}

		// 获取图片在库中的位置
		public Object getItem(int position) {
			return position;
		}

		// 获取图片ID
		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if (convertView == null) {
				// 给ImageView设置资源
				imageView = new ImageView(mContext);
				// 设置布局 图片120×120显示
				imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
				// 设置显示比例类型
				imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
			} else {
				imageView = (ImageView) convertView;
			}

			int imageKey = mContext.getResources().getIdentifier(dataSource.get(position).getIcon(), "drawable", mContext.getPackageName());
			imageView.setImageResource(imageKey);
			return imageView;
		}
	}

}
